package com.xiaoquan.gulimall.ssoclient.controller;

import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @authro dxq
 * @date 2021年07月16日 0:53
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    String ssoServerUrl;

    /**
     * 测试：多次的request，如何共享数据
     * @return
     */
    @ResponseBody
    @GetMapping("world")
    public String world(@RequestParam(value = "firstInfo",required = false) String firstInfo ,HttpSession session) {
        if(!StringUtils.isEmpty(firstInfo)){
            session.setAttribute("firstInfo", firstInfo);
        }
        Object obj = session.getAttribute("firstInfo");
        System.out.println(obj);
        return "world";
    }

    @ResponseBody
    @GetMapping(value = "/hello")
    public String hello(HttpSession session) {


        return "hello";
    }

    /**
     * 感知这次是在 ssoserver 登录成功调回来的
     * @param model
     * @param session
     * @param token  required = false 非必须参数（可有可无）  只要去ssoserver登录成功跳回来 就会带上token标识
     * @return
     */
    @GetMapping(value = "/employees")
    public String employees(HttpServletRequest request, Model model, HttpSession session, @RequestParam(value = "token", required = false) String token) {
        if (!StringUtils.isEmpty(token)) {
            // 去ssoserver获取当前token真正对应的用户信息
            RestTemplate restTemplate=new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://127.0.0.1:9090/userInfo?token=" + token, String.class);
            String body = forEntity.getBody();

            session.setAttribute("loginUser", body);
        }
        Object loginUser = session.getAttribute("loginUser");

        if (loginUser == null) {
            // 没登录，跳转到登陆服务器进行登录
            return "redirect:" + ssoServerUrl+"?redirect_url=http://127.0.0.1:9091/employees";
        } else {
            List<String> emps = new ArrayList<>();

            emps.add("张三");
            emps.add("李四");

            model.addAttribute("emps", emps);
            return "employees";
        }
    }
}
